import { AfterViewInit, Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { OnReuseDestroy, OnReuseInit, ReuseHookOnReuseInitType } from '@delon/abc/reuse-tab';
import { STComponent } from '@delon/abc/st';
import { SFComponent, SFSchema } from '@delon/form';
import { SearchDrawerService } from '@shared';
import { fromEvent, Subscription } from 'rxjs';
import { debounceTime } from 'rxjs/operators';

/**
 * 列表基础组件
 * 功能：
 *  1、计算列表滚动高度（scrollY）
 *      实现：
 *        1、列表组件需继承BasicTableComponent，并且提供SearchDrawerService派生类
 *        2、引入commom-table.less 样式文件
 *        3、列表使用table-box class包裹。组件会自动减去layout-pro-header、page-header-wrapper和nz-tabs-nav标签的高度，以及header_box和height_box class的高度，最后减去deviationHeight的偏移高度
 *  2、提供筛选抽屉，并返回sf实例（sf）
 *      实现：
 *        1、列表组件需继承BasicTableComponent，并且提供SearchDrawerService派生类
 *        2、实例化schema，及给schema赋值sf配置
 *        3、重写search()方法。当筛选抽屉触发查询时会调用这个方法
 *      提供：
 *        1、抽屉的sf实例
 *        2、sf.value的数据=>sfValue
 */
@Component({
  template: ``
})
export class BasicTableComponent implements AfterViewInit, OnDestroy, OnReuseDestroy, OnReuseInit {
  scrollY = '400px';

  sf!: SFComponent;
  sfValue: Record<string, any> = {};
  schema: SFSchema = {};

  deviationHeight = 0;

  @ViewChild('st', { static: true })
  st!: STComponent;

  constructor(public searchDrawerService: SearchDrawerService) {}
  _onReuseInit(type?: ReuseHookOnReuseInitType): void {
    if (this.st) {
      this.st.load(this.st.pi);
    }
    // this.search();
  }

  ngAfterViewInit(): void {
    setTimeout(() => {
      this.getScrollY();
    }, 100);
    fromEvent(window, 'resize')
      .pipe(debounceTime(100))
      .subscribe(event => {
        this.getScrollY();
      });
  }

  _onReuseDestroy(): void {
    // this.drawer.forEach(sub => sub.unsubscribe());
  }

  ngOnDestroy(): void {
    this.searchDrawerService.unsubscribe();
  }

  openDrawer() {
    const drawer = this.searchDrawerService.created({ ...this.sfValue }, this.schema, this);

    drawer.afterOpen.subscribe(_ => {
      if (drawer.getContentComponent()?.sf) {
        this.sf = drawer.getContentComponent()?.sf as SFComponent;
      }
    });
    // drawer.afterClose.subscribe((res: Record<string, any>) => {
    //   this.sfValue = { ...this.sfValue, ...res };
    //   console.log(this.sfValue);
    //   if (res) {
    //     this.search();
    //   }
    // });
    // if (this.searchDrawerService.drawer?.length > 0) {
    //   // this.searchDrawerService.created();
    //   this.searchDrawerService.create(this.sfValue, this.schema);
    // } else {
    //   const drawer = this.searchDrawerService.create(this.sfValue, this.schema);
    //   this.searchDrawerService.drawer.push(
    //     drawer.initEvent.subscribe((sf: SFComponent) => {
    //       if (sf) {
    //         this.sf = sf;
    //       }
    //     })
    //   );
    //   this.searchDrawerService.drawer.push(
    //     drawer.closeEvent.subscribe((res: Record<string, any>) => {
    //       this.sfValue = res;
    //       if (res) {
    //         this.search();
    //       }
    //     })
    //   );
    // }
  }

  getScrollY() {
    const windowHeight = window.innerHeight || Math.max(document.documentElement.clientHeight, document.body.clientHeight);
    const header = document.getElementsByTagName('layout-pro-header')?.[0];
    if (windowHeight && header) {
      let scrollY = windowHeight - header.clientHeight - 35 - 49 - 20;
      // 剔除页头高度
      const headerWrapper = document.getElementsByTagName('page-header-wrapper')?.[0];
      if (headerWrapper) {
        scrollY -= headerWrapper.clientHeight;
      }
      // 计算所有tabs高度
      const tabset = document.getElementsByTagName('nz-tabs-nav');
      let tabsetHeight = 0;
      for (let index = 0; index < tabset.length; index++) {
        tabsetHeight += tabset[index].clientHeight;
      }
      if (tabset) {
        scrollY -= tabsetHeight;
      }
      // 剔除高度容器
      const headerBox = document.getElementsByClassName('header_box');
      let headerBoxHeight = 0;
      for (let index = 0; index < headerBox.length; index++) {
        headerBoxHeight += headerBox[index].clientHeight;
      }
      if (headerBox) {
        scrollY -= headerBoxHeight;
      }

      // 剔除高度容器
      const heightBox = document.getElementsByClassName('height_box');
      let heightBoxHeight = 0;
      for (let index = 0; index < heightBox.length; index++) {
        heightBoxHeight += heightBox[index].clientHeight;
      }
      if (heightBox) {
        scrollY -= heightBoxHeight;
      }

      if (typeof this.deviationHeight === 'number') {
        scrollY -= this.deviationHeight;
      }
      this.scrollY = scrollY + 'px';
    }
  }

  search() {}
}
